網站:https://laihao2.com/
新增功能
這篇繼續先說明新增功能:
就是畫面上的Create New
ASP.NET開發操作流程:資料表設定好>再寫程式:加入資料庫>串聯資料庫>產生Models裡面類別檔dao>按:建置>Controllers裡面的Entities>產生畫面View
資料表在上一篇已經建立,所以這裡從Controllers裡面的Entities>
Controllers程式碼
[HttpPost]
        public ActionResult Create(Product product)
        {
            // 取得上一筆單據的單據編號
            var lastProduct = _db.Products.OrderByDescending(p => p.data).FirstOrDefault();
            string lastNumber = lastProduct?.單據編號;
            // 產生新的單據編號
            string newNumber;
            if (string.IsNullOrEmpty(lastNumber))
            {
                // 如果是第一筆資料, 單據編號為 "20230406001"
                newNumber = $"{DateTime.Now.ToString("yyyyMMdd")}001";
            }
            else
            {
                // 如果不是第一筆資料, 單據編號自動遞增
                int lastNumberInt = int.Parse(lastNumber.Substring(8));
                newNumber = $"{DateTime.Now.ToString("yyyyMMdd")}{(lastNumberInt + 1).ToString("D3")}";
            }
            product.單據編號 = newNumber;
            product.data = DateTime.Now; // 設置 data 欄位為目前日期時間
            if (_db.Products.Where(m => m.編號 == product.編號).FirstOrDefault() == null)
            {
                _db.Products.Add(product);
                _db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.Msg = "編號重複!";
            return View();
        }
解釋程式碼
這段代碼定義了一個 ASP.NET MVC 控制器中用於創建 Product 的兩個動作方法,分別用於處理 GET 請求和 POST 請求,主要負責生成新的單據編號並將新的產品數據存入數據庫。以下是詳細解釋:
public ActionResult Create():Create 動作方法。Create 頁面時,這個方法會被調用,並返回一個空白的表單視圖,供用戶輸入新產品的信息。return View();:返回對應的視圖頁面,顯示創建產品的表單。[HttpPost] public ActionResult Create(Product product):Create 動作方法。當用戶提交產品創建表單時,表單數據會通過 POST 請求發送到該方法。Product product: 通過模型綁定機制,將表單中輸入的數據映射到 Product 對象。var lastProduct = _db.Products.OrderByDescending(p => p.data).FirstOrDefault();
string lastNumber = lastProduct?.單據編號;
Products 表,按 data 列(日期)降序排列,獲取最後一筆產品記錄,並提取該記錄的 單據編號。lastProduct 為 null,並且 lastNumber 也會是 null。string newNumber;
if (string.IsNullOrEmpty(lastNumber))
{
    // 如果是第一筆資料, 單據編號為 "20230406001"
    newNumber = $"{DateTime.Now.ToString("yyyyMMdd")}001";
}
else
{
    // 如果不是第一筆資料, 單據編號自動遞增
    int lastNumberInt = int.Parse(lastNumber.Substring(8));
    newNumber = $"{DateTime.Now.ToString("yyyyMMdd")}{(lastNumberInt + 1).ToString("D3")}";
}
lastNumber 為空),系統會生成一個默認的編號格式 yyyyMMdd001,例如 20230406001。單據編號,將最後三位數字部分遞增 1 以生成新的編號。例如,上一筆的編號是 20230406001,那麽新的編號將會是 20230406002。product.單據編號 = newNumber;
product.data = DateTime.Now; // 設置 data 欄位為目前日期時間
單據編號 賦值給當前 Product 對象。data 字段設置為當前的日期和時間。if (_db.Products.Where(m => m.編號 == product.編號).FirstOrDefault() == null)
{
    _db.Products.Add(product);
    _db.SaveChanges();
    return RedirectToAction("Index");
}
編號 相同的記錄。如果不存在重覆記錄,則將新產品數據添加到數據庫中並保存 (SaveChanges()),然後重定向到 Index 頁面。ViewBag.Msg = "編號重複!";
return View();
編號 重覆,則通過 ViewBag 傳遞一條 "編號重複!" 的提示消息,並重新返回創建視圖,提示用戶編號已存在,要求重新輸入。這段代碼的主要功能是在創建新產品時自動生成唯一的單據編號,防止編號重覆並將數據保存到數據庫中。如果輸入的 編號 已存在,則會提示錯誤並讓用戶重新輸入。
產生畫面View
View程式碼
@model WebApplication5.Models.Product
@{
    ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
<div class="form-horizontal">
    <h4>Product</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.編號, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.編號, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.編號, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.品名, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.品名, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.品名, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.單價, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.單價, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.單價, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        @Html.LabelFor(model => model.備註, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.備註, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.備註, "", new { @class = "text-danger" })
        </div>
    </div>
    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}
@if (ViewBag.Msg != null)
{
    <div class="alert alert-danger">
        @ViewBag.Msg
    </div>
}
<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}
解釋程式碼
這段代碼是一個 ASP.NET MVC 的視圖文件,用於生成一個表單頁面,供用戶創建 Product(產品)對象。該視圖主要是一個 HTML 表單,利用 Razor 語法和 HtmlHelper 方法與模型進行交互。以下是對代碼的詳細解釋:
@model WebApplication5.Models.ProductProduct 模型。視圖通過模型與表單字段關聯,用戶填寫的數據將映射到 Product 對象中。@{ ViewBag.Title = "Create"; }@using (Html.BeginForm())Html.BeginForm() 方法生成一個 HTML <form> 標簽。Create 動作方法。@Html.AntiForgeryToken():生成一個防偽標記,防止跨站請求偽造 (CSRF) 攻擊。每個字段的創建都遵循相同的結構:
<div class="form-group">
    @Html.LabelFor(model => model.編號, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.編號, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.編號, "", new { @class = "text-danger" })
    </div>
</div>
@Html.LabelFor(model => model.編號): 生成一個與模型屬性 編號 相關聯的 <label> 標簽。@Html.EditorFor(model => model.編號): 生成一個輸入控件,用於用戶輸入 編號 值。htmlAttributes 用於為該控件添加 HTML 樣式類。@Html.ValidationMessageFor(model => model.編號): 用於顯示表單字段的驗證錯誤消息。類 text-danger 使消息顯示為紅色。類似的代碼用於其他字段(如 品名、單價 和 備註),以實現輸入框和標簽的自動生成和驗證。
<div class="form-group">
    <div class="col-md-offset-2 col-md-10">
        <input type="submit" value="Create" class="btn btn-default" />
    </div>
</div>
<input type="submit"> 會生成一個提交按鈕,點擊後表單會通過 POST 請求發送。@if (ViewBag.Msg != null)
{
    <div class="alert alert-danger">
        @ViewBag.Msg
    </div>
}
ViewBag.Msg 中有內容(例如前端收到控制器中的 "編號重複" 錯誤信息),則顯示一個紅色的提示框。<div>
    @Html.ActionLink("Back to List", "Index")
</div>
@Html.ActionLink("Back to List", "Index") 生成一個超鏈接,鏈接的文本是 "Back to List",點擊後會跳轉到 Index 動作方法,通常返回產品列表頁面。@section Scripts { @Scripts.Render("~/bundles/jqueryval") }Scripts 區域引入腳本資源,主要是 jQuery 和驗證腳本 (jqueryval)。這段代碼通過表單讓用戶創建一個 Product 對象。表單會根據用戶輸入的數據自動生成相應的 HTML 元素,並且結合驗證機制確保輸入合法。同時,視圖中包含錯誤提示、提交按鈕,以及一個返回列表的鏈接。
在網頁上看到https://laihao2.com/Home/Create
下載功能
其實就是使用WORD的合併列印
下一步
下一步
資料表在上一篇已經建立,所以這裡從Controllers裡面的Entities>
 	public FileResult DownloadTemplate()
 	        {
 	            // 指定 templates 資料夾的路徑
 	            string filePath = Server.MapPath("~/templates/範本.docx");
 	            // 回傳檔案供下載
 	            return File(filePath, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "範本.docx");
 	        }
解釋程式碼
這段代碼是一個 ASP.NET MVC 控制器中的 DownloadTemplate 動作方法,負責處理文件下載請求。它的作用是從服務器指定目錄獲取一個 Word 文檔,並返回給用戶進行下載。以下是對這段代碼的詳細解釋:
public FileResult DownloadTemplate()FileResult 類型的動作方法。FileResult 是 ASP.NET MVC 中的一種返回類型,專門用於處理文件下載請求。string filePath = Server.MapPath("~/templates/範本.docx");Server.MapPath() 方法用於將相對路徑轉換為服務器上的絕對路徑。它將相對路徑 "~/templates/範本.docx" 轉換為服務器上對應的物理文件路徑。"~/templates/範本.docx":這是相對於網站根目錄的文件路徑,表示位於 templates 文件夾中的 範本.docx 文件。return File(filePath, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "範本2本機.docx");File() 方法用於將指定的文件返回給客戶端。它有三個參數:
filePath: 文件的物理路徑,也就是服務器上要下載的文件位置。"application/vnd.openxmlformats-officedocument.wordprocessingml.document": 這是文件的 MIME 類型,表示文件是 Word 文檔(.docx 格式)。"範本2本機.docx": 這是用戶在下載文件時看到的文件名,也就是文件下載後在本地保存時的名稱。DownloadTemplate 動作的請求。Server.MapPath 找到 範本.docx 文件在服務器上的實際存儲位置。"範本2本機.docx"。這個方法實現了從服務器上下載一個 Word 文檔。通過 Server.MapPath 找到文件的物理位置,再通過 File() 方法將文件返回給客戶端,下載時使用指定的文件名。
到網站https://laihao2.com/
這裡對照昨天INDEX畫面程式碼
@model IEnumerable<WebApplication5.Models.Product>
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
    @Html.ActionLink("Create New", "Create")
</p>
<p>
    @Html.ActionLink("下載範本", "DownloadTemplate", "Home")
</p>
<h3>使用SOP</h3>
<ol>
    <li>
        按"下載範本"右上顯示下載
    </li>
    <li>
        開啟檔案
    </li>
    <li>
        word上方工作列選"郵件"
    </li>
    <li>
        工作列選"郵件"看"預覽結果"
    </li>
    <li>
        "預覽結果"依序選擇
    </li>
    <li> 列印word
    </li>
</ol>
        <table class="table">
            <tr>
                <th>
                    序號
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.編號)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.品名)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.單價)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.備註)
                </th>
                <th></th>
            </tr>
            @{
                int counter = 1;
            }
            @foreach (var item in Model)
            {
                <tr>
                    <td>@(counter++)</td>
                    <td>
                        @Html.DisplayFor(modelItem => item.編號)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.品名)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.單價)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.備註)
                    </td>
                    @*
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { id = item.編號 }) |
                        @Html.ActionLink("Details", "Details", new { id = item.編號 }) |
                        @Html.ActionLink("Delete", "Delete", new { id = item.編號 })
                    </td>*@
                </tr>
            }
        </table>
產生畫面View的程式碼就是上面的
 	<p>
 	    @Html.ActionLink("下載範本", "DownloadTemplate", "Home")
 	</p>
解釋程式碼
這段代碼是一個 ASP.NET MVC 的視圖部分,用來創建一個鏈接,允許用戶點擊後執行一個控制器的動作方法。這是對這段代碼的解釋:
<p>
    @Html.ActionLink("下載範本", "DownloadTemplate", "Home")
</p>
@Html.ActionLink@Html.ActionLink() 是一個幫助方法,用來生成 HTML 的超鏈接 (<a> 標簽)。HomeController 中的 DownloadTemplate 動作方法。HomeController。HomeController 的 DownloadTemplate 動作。DownloadTemplate 方法,這個鏈接的作用是讓用戶下載一個模板文件(例如 Word 文件)。大家明天見~